<?php
// TODO: dodawanie, edytowanie, usuwanie kategorii
session_start();
class Controller_Admin_Category extends Controller_Admin_Abstract
{

	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('admin_category', $frontController);
	}
	
	public function indexAction()
	{
		$this->display('admin_category.tpl');
	}
	
	public function newAction()
	{
		$category;
		$buttonName;
		$tags = '';
		
		if (isset($_GET['id_category'])) {
			$id = $_GET['id_category'];
			$buttonName = 'Edytuj';
			
			$category = CategoriesPeer::retrieveByPK($id);
			
			$tags = Manager_Category::getTags($category);
			$tagsString = '';
			
			foreach ($tags as $tag) {
				$tagsString .= $tag->getName() . ', ';
			}
			
			$tags = $tagsString;
		} else {
			$buttonName = 'Dodaj';
			$category = new Categories();
		}
		$this->view()->assign('category', $category);
		$this->view()->assign('editButton', $buttonName);
		$this->assign('tags', $tags);
		$_SESSION['enable']=true;
		$this->view()->display('admin_category_edit.tpl');
	}
	
	public function listAction()
	{
		$categories = CategoriesPeer::doSelect(new Criteria());
		//var_dump($categories);
		$this->view()->assign('categories', $categories);
		
		$this->view()->display('admin_category_list.tpl');
	}
	
	public function checkAction()
	{		
		$category;
		
		if (!empty($_POST['id_category'])) {
			$id = $_POST['id_category'];
			
			$category = CategoriesPeer::retrieveByPK($id);
		} else {
			$category = new Categories();
		}
		
		
		if($_SESSION["enable"]==true) {
			$category->setName($_POST['name']);
			$category->setDescription($_POST['description']);
			$tags = Manager_Tag::add(Manager_Tag::fromString($_POST['tags']));			
			Manager_Category::setTags($category, $tags);
			$category->save();
			$this->ok('Category saved.');	
			$_SESSION['enable']=false;		
		} else {
			$this->fail('Re-saving it is not possible.');
		}
		
	}	
	
	public function deleteAction()
	{
		
		if (!isset($_GET['id_category'])) {
			throw new Exception('id not spec');
		}	
		
		$id = $_GET['id_category'];
		try {
			CategoriesPeer::doDelete($id);
		} catch (Exception $e) {
			$this->view()->assign('fail_info', 'Nie udalo sie usunac ' 
				. $e->getMessage());  	
			return $this->view()->display('fail.tpl');		
		}
				
			
	}
	
}